import { useEffect, useRef } from 'react';

import { Router, useRouter } from 'next/router';

/*
Сохраняет в реф позицию скролла
*/

export const usePreserveScroll = () => {
  const router = useRouter();
  const scrollPositions = useRef<{ [url: string]: number }>({});
  const isBack = useRef(false);
  useEffect(() => {
    const onRouteChangeStart = () => {
      const url = router.pathname;
      scrollPositions.current[url] = window.scrollY;
    };
    const onRouteChangeComplete = (url: any) => {
      router.beforePopState(() => {
        isBack.current = true;
        return true;
      });
      if (isBack.current) {
        window.scroll({
          top: scrollPositions.current[url],
          behavior: 'auto',
        });
      }
      isBack.current = false;
    };
    Router.events.on('routeChangeStart', onRouteChangeStart);
    Router.events.on('routeChangeComplete', onRouteChangeComplete);
    return () => {
      Router.events.off('routeChangeStart', onRouteChangeStart);
      Router.events.off('routeChangeComplete', onRouteChangeComplete);
    };
  }, [router]);
};
